import { useLayoutEffect, useRef } from 'react'
import { useThree } from '@react-three/fiber'
import { Box3, Vector3, type Object3D } from 'three'

interface UseModelAutoCenterOptions {
  /** 模型对象 */
  model: Object3D | null
  /** 距离系数，默认 2.5 */
  distanceFactor?: number
  /** 是否启用自动居中 */
  enabled?: boolean
  /** 位置偏移量 避免重叠 */
  positionOffset?: [number, number, number]
}
export function useModelAutoCenter({
  model,
  distanceFactor = 2.5,
  enabled = true,
  positionOffset = [0, 0, 0],
}: UseModelAutoCenterOptions) {
  const { camera } = useThree()
  const meshRef = useRef<Object3D>(null)



  useLayoutEffect(() => {
    if (!enabled || !model || !meshRef.current) return

    const box = new Box3()
    box.setFromObject(model)

    if (box.isEmpty()) return

    const center = box.getCenter(new Vector3())
    const modelSize = box.getSize(new Vector3())
    const maxDim = Math.max(modelSize.x, modelSize.y, modelSize.z)
    const distance = maxDim * distanceFactor

    // 将模型中心移动到原点，然后加上位置偏移，避免重叠
    if (meshRef.current) {
      meshRef.current.position.x = -center.x + positionOffset[0]
      meshRef.current.position.y = -center.y + positionOffset[1]
      meshRef.current.position.z = -center.z + positionOffset[2]
    }

    // 调整相机位置
    if (positionOffset[0] === 0 && positionOffset[1] === 0 && positionOffset[2] === 0) {
      camera.position.set(0, 0, distance)
      camera.lookAt(0, 0, 0)
      camera.updateProjectionMatrix()
    }
  }, [model, camera, distanceFactor, enabled, positionOffset])

  return meshRef
}
